package com.hrt.datasender.datadao.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.btcode.db.sqlparameter.SQLParameterList;
import com.hrt.datasender.datadao.model.BdSendRecordModel;
import com.hrt.datasender.datastorage.StorageDataType;
import com.hrt.datasender.web.WebMain;
import com.hrt.db.DBManager;

public final class BdSendRecordService {

    private static volatile BdSendRecordService instance;

    private BdSendRecordService() {

    }

    public static BdSendRecordService getInstance() {
        if (instance == null) {
            synchronized (BdSendRecordService.class) {
                if (instance == null) {
                    instance = new BdSendRecordService();
                }
            }
        }
        return instance;
    }

    public Date getLastSendDate(StorageDataType dataType, String ip, String port) {
        String sql = "SELECT * FROM BD_SEND_RECORD WHERE IP='" + ip + "' AND PORT='" + port + "' AND DATA_TYPE='"
                + dataType + "'";
        Date date = new Date();

        List<BdSendRecordModel> list = DBManager.getORMExecuter().getModelListSQL(sql, null, BdSendRecordModel.class);
        if (list.size() < 1) {
            BdSendRecordModel model = new BdSendRecordModel();
            model.setIp(ip);
            model.setPort(port);
            model.setDataType(dataType.toString());
            model.setId(model.getIp() + "_" + model.getPort() + "_" + model.getDataType());
            model.setDataReadtime(date);
            DBManager.getORMExecuter().create(model);
        }
        else {
            date = list.get(0).getDataReadtime();
        }
        return date;
    }

    public void updateLastSendDate(StorageDataType dataType, String ip, String port, Date date) {

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateText = sf.format(date);

        String sql;
        if("mysql".equals(WebMain.DBTYPE)){
           sql = "UPDATE BD_SEND_RECORD SET DATA_READTIME='" + dateText + "',DATA_READTIME_TEXT='" + dateText
                + "' WHERE IP='" + ip + "' AND PORT='" + port + "' AND DATA_TYPE='" + dataType + "'";
        }
        else{
            sql = "UPDATE BD_SEND_RECORD SET DATA_READTIME=" + date.getTime() + ",DATA_READTIME_TEXT='" + dateText
                + "' WHERE IP='" + ip + "' AND PORT='" + port + "' AND DATA_TYPE='" + dataType + "'";
        }

        DBManager.getDataExecuter().update(sql, null);
    }

    public void updateSendRecordQn(StorageDataType dataType, String ip, String port,String qn){
        String sql = "UPDATE BD_SEND_RECORD" +
                "   SET QN = '"+qn+"'" +
                " where IP = '"+ip+"'" +
                "   and PORT = '"+port+"'" +
                "   and DATA_TYPE = '"+dataType+"'";
        DBManager.getDataExecuter().update(sql,null);
    }

}